import React, { createContext, useState, useContext, useEffect } from 'react';
import AuthService from '../services/authService'; // Corrected path: ../services/authService.js

const AuthContext = createContext(null);

export const AuthProvider = ({ children }) => {
    const [currentUser, setCurrentUser] = useState(AuthService.getCurrentUser());
    const [loading, setLoading] = useState(true); 

    useEffect(() => {
        const user = AuthService.getCurrentUser();
        if (user) {
            setCurrentUser(user);
        }
        setLoading(false); 
    }, []);

    const login = async (username, password) => {
        try {
            const userData = await AuthService.login(username, password);
            setCurrentUser(userData);
            return userData;
        } catch (error) {
            console.error("Login failed:", error.response ? error.response.data : error.message);
            throw error;
        }
    };

    const logout = () => {
        AuthService.logout();
        setCurrentUser(null);
        // Consider using React Router's navigate for programmatic navigation
        // For example, if you have access to navigate function: navigate('/login');
    };

    const register = async (userData) => {
        try {
            const response = await AuthService.register(userData);
            return response.data; 
        } catch (error) {
            console.error("Registration failed:", error.response ? error.response.data : error.message);
            throw error;
        }
    };

    // Memoize the value to prevent unnecessary re-renders of consumers
    // This is a good practice but not strictly necessary for this small context
    const value = React.useMemo(() => ({
        currentUser,
        isAuthenticated: !!currentUser,
        login,
        logout,
        register,
        loading 
    }), [currentUser, loading]);

    return <AuthContext.Provider value={value}>{!loading && children}</AuthContext.Provider>;
};

export const useAuth = () => {
    const context = useContext(AuthContext);
    if (context === undefined) {
        throw new Error('useAuth must be used within an AuthProvider');
    }
    return context;
};

// 检查用户是否有特定角色
const hasRole = (requiredRole) => {
  const token = localStorage.getItem('token');
  if (!token) return false;
  
  try {
    // 调试JWT解析
    console.log("检查角色，当前token:", token);
    const tokenParts = token.split('.');
    if (tokenParts.length !== 3) {
      console.error("Token格式不正确");
      return false;
    }
    
    // 解析JWT payload
    const payload = JSON.parse(atob(tokenParts[1]));
    console.log("Token payload:", payload);
    
    // 检查用户角色
    if (payload.roles && Array.isArray(payload.roles)) {
      return payload.roles.includes(requiredRole);
    }
    return false;
  } catch (error) {
    console.error("解析JWT时出错:", error);
    return false;
  }
}; 